﻿using Bing.Maps;
using Windows.Devices.Geolocation;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace BingMapsIntro_WinRT_CS
{
    public sealed partial class MainPage : Page
    {
        Geolocator geolocator;
        GpsIcon GpsPushpin;

        public MainPage()
        {
            this.InitializeComponent();

            //CReate a pushpin for the GPS location and add it to the map
            GpsPushpin = new GpsIcon(MyMap)
            {
                Visibility = Windows.UI.Xaml.Visibility.Collapsed
            };

            MyMap.Children.Add(GpsPushpin);
        }

        private void GPS_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;

            if (cb.IsChecked.HasValue && cb.IsChecked.Value)
            {
                if (geolocator == null)
                {
                    //Create an instance of the GeoLocator class.
                    geolocator = new Geolocator();
                }

                //Add the position changed event
                geolocator.PositionChanged += geolocator_PositionChanged;
            }
            else
            {
                if (geolocator != null)
                {
                    //Remove the position changed event
                    geolocator.PositionChanged -= geolocator_PositionChanged;
                }

                //Hide the GPS pushpin
                GpsPushpin.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
        }

        private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            // Need to get back onto UI thread before updating location information
            this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(
            () =>
            {
                //Get the current location
                Location location = new Location(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude);

                //Update the position of the GPS pushpin
                MapLayer.SetPosition(GpsPushpin, location);
                
                //Set the radius of the Accuracy Circle
                GpsPushpin.SetRadius(args.Position.Coordinate.Accuracy);

                //Make GPS pushpin visible
                GpsPushpin.Visibility = Windows.UI.Xaml.Visibility.Visible;

                //Update the map view to the current GPS location
                MyMap.SetView(location, 17);
            }));
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }
    }
}
